import {Component, ChangeDetectorRef, OnInit} from "@angular/core";
import {
  NavController,
  NavParams,
  ActionSheetController,
  ToastController,
  AlertController
} from "ionic-angular";
import { Storage } from "@ionic/storage";
import { HttpService } from "../../../providers/http.service";
import { Camera, CameraOptions } from "@ionic-native/camera";
import { CommonFunc } from "../../../providers/commonFunc";
import { WorkSumPage } from "../../work-sum/work-sum";
import { appConfig } from "../../../providers/config";
import { SelfCheckTractionBean} from "../bean/self-check-traction.bean";

import {
  FileTransfer,
  FileUploadOptions,
  FileTransferObject
} from "@ionic-native/file-transfer";
import { File } from "@ionic-native/file";
import * as moment from "moment";
import { PhotoViewer } from "@ionic-native/photo-viewer";
import { HomePage } from "../../home/home";
import {getHostElement} from "@angular/core/src/render3";
import {SelfCheckResultBean} from "../bean/self-check-result.bean";

@Component({
  selector: "page-self-check-traction",
  templateUrl: "self-check-traction.html",
  // styleUrls: ["self-check-traction.scss"]
})
export class SelfCheckTractionPage implements OnInit{
  private showOK: boolean = false;
  private showError: boolean = false;
  private appConfig: any;
  private selfCheckBean: SelfCheckTractionBean = new SelfCheckTractionBean();
  private user: any;
  elevatorType: string;
  time1 = new Date().getTime() + "1";
  time2 = new Date().getTime() + "2";
  item_details: any = [];
  private checkItemList : any = [];
  constructor(
    public navCtrl: NavController,
    private storage: Storage,
    private httpService: HttpService,
    private camera: Camera,
    private commonFunc: CommonFunc,
    private transfer: FileTransfer,
    private file: File,
    private navParams: NavParams,
    private photoViewer: PhotoViewer,
    private ActionSheet: ActionSheetController,
    public cd: ChangeDetectorRef,
    public toast: ToastController,
    public alertController: AlertController,
  ) {
    this.appConfig = appConfig;
    this.elevatorType = this.navParams.get("elevatorType");
    this.storage.get("user").then(data => {
      this.user = data;
    });
    this.selfCheckBean.checkTime = moment(new Date()).format("YYYYMMDDHHmmss");
  }

  ngOnInit(): void {
    this.getCheckItems();
    // this.hideCheckItemDesc();
  }

  /**
   * 处理检查项项详情长度超过200时展示部分
   */
  hideCheckItemDesc(){
    // let ids:string = ["onePointFour",]
    let items =  document.getElementsByTagName("p");
    console.log(document.getElementsByClassName("check_item_desc")[0]);
    // let items =  document.getElementById("onePointFour");
    console.log(items);
    console.log(items.length);
    console.log(items.item(0).innerHTML);
    // console.log(items[0].children[0].innerHTML);
    // console.log(items[0].innerHTML);
    /*for(let j = 0; j < items.length; j++){
      let tags = items[j].getElementsByTagName("p");
      console.log(tags.length);
      console.log(tags);
      for(let i = 0;i < tags.length ; i++){
        let tag = tags.item(i);
        let text =tag.innerText;
        console.log(text);
        if(text.length > 200){
          let newBox = document.createElement("div");
          newBox.innerHTML = text.substring(0,200);
          let btn = document.createElement("a");
          btn.innerHTML = "...展开全部内容";
          btn.href = "###";
          btn.onclick = function (){
            if( btn.innerHTML == "...展开全部内容"){
              btn.innerHTML = "收起"
              newBox.innerHTML = text;
            }else{
              btn.innerHTML = "...展开全部内容";
              newBox.innerHTML = text.substring(0,200);
            }
            return false;
          }
          tag.innerHTML = "";
          tag.appendChild(newBox);
          tag.appendChild(btn);
        }
      }
    }*/
  }

  /**
   * 获取所有电梯的检查项与检查项详情
   */
  getCheckItems(){
    let itemName = '曳引与强制驱动电梯';
    let params = { itemType: "5", itemName: itemName};
    this.httpService.queryCheckItem(params).subscribe(data => {
      if (data.status == 200) {
        this.checkItemList = data.data.list;
        this.checkItemList.forEach(element => {
          this.item_details[element.itemKey] = element.ext2;
        });
      }
    });
  }

  /**
   * 展示与收缩div
   * @param name
   */
  contractOrExpanse(name){
    if(document.getElementById(name).style.display == 'none'){
      document.getElementById(name).style.display = '';
    }else{
      document.getElementById(name).style.display = 'none';
    }

  }

  /**
   * 处理检查结果成行数据
   */

  getCheckResults(){
    let checkResults : any = [];
    let tempCheckItemList = this.checkItemList;
    for(let i = 0; i < tempCheckItemList.length; i++){
      let selfCheckResult : SelfCheckResultBean = new SelfCheckResultBean();
      selfCheckResult.checkItemId = tempCheckItemList[i].id;
      selfCheckResult.checkItemName = tempCheckItemList[i].itemContent;
      for (let selfCheckBeanKey in this.selfCheckBean) {
        if(tempCheckItemList[i].itemKey == selfCheckBeanKey){
          selfCheckResult.checkResult =  JSON.stringify(this.selfCheckBean[selfCheckBeanKey]);
          continue;
        }
      }
      checkResults.push(selfCheckResult);
    }
    this.selfCheckBean.checkResults = checkResults;
  }


  /**
   * 提交检查结果
   */
  doSubmit() {

    let list = ["pic1", "pic2", "pic3"]
    if (this.commonFunc.vlidate(this.selfCheckBean, list, false)) {
      if (
          this.selfCheckBean.isPass == undefined ||
          this.selfCheckBean.isPass == null
      ) {
        let tt = this.toast.create({
          message: "请选择是否合格",
          duration: 2000,
          position: "top"
        });
        tt.present();
        return;
      }
      if (!this.selfCheckBean.maintUserSign) {
        let tt = this.toast.create({
          message: "请检查人签名",
          duration: 2000,
          position: "top"
        });
        tt.present();
        return;
      }
      if (!this.selfCheckBean.safeUserSign) {
        let tt = this.toast.create({
          message: "请使用单位电梯管理员签名",
          duration: 2000,
          position: "top"
        });
        tt.present();
        return;
      }

      this.getCheckResults();
      this.selfCheckBean.elevatorId = this.navParams.get("elevatorId");
      this.selfCheckBean.elevatorNum = this.navParams.get("elevatorNum");
      this.selfCheckBean.maintPartyName = this.user.partyName;
      this.selfCheckBean.maintPartyId = this.user.partyId;
      this.selfCheckBean.maintPartyName = this.user.partyName;
      this.selfCheckBean.maintUserName = this.user.userName;
      this.selfCheckBean.maintUserId = this.user.id;

      this.httpService.addSelfCheckRecord(
          this.commonFunc.convertBeanToString(this.selfCheckBean)
      )
          .subscribe(data1 => {
            if (data1.status == 200) {
              let tt = this.toast.create({
                message: "提交成功",
                duration: 3000,
                position: "top"
              });
              tt.present().then(() => {
                this.navCtrl.setRoot(HomePage).then(() => {
                  window["jQuery"](`#` + this.time1 + `1`).remove();
                  window["jQuery"](`#` + this.time1 + `2`).remove();
                  window["jQuery"](`#` + this.time2 + `1`).remove();
                  window["jQuery"](`#` + this.time2 + `2`).remove();
                  this.navCtrl
                      .getActive()
                      .getNav()
                      .remove(0);
                });
              });
            } else {
              this.commonFunc.convertBean(this.selfCheckBean);
              const alert = this.alertController.create({
                subTitle: "信息保存失败",
                buttons: ["确定"]
              });
              alert.present();
            }
          });
    } else {
      let toas = this.commonFunc.showInsideErrorToast({
        errorMessage: "请拍完所有照片"
      });
      toas.present();
      return;
    }
  }

  doOk(name) {
    this.selfCheckBean[name].isOk = !this.selfCheckBean[name].isOk;
    this.cd.detectChanges();
  }

  doIsNull(name){
    this.selfCheckBean[name].isOk = null;
    this.cd.detectChanges();
  }

  doError(name) {
    this.selfCheckBean[name].isOk = !this.selfCheckBean[name].isOk;
  }

  doCamera(name, i) {
    let options: CameraOptions = {
      quality: 85, // destinationType: this.camera.DestinationType.DATA_URL,
      // encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
      targetWidth: 1500,
      targetHeight: 1500,
      correctOrientation: true
    };
    this.camera.getPicture(options).then(imageData => {
      //判断网络状态
      if (!this.commonFunc.hasNetWork()) {
        if (i == "c") {
          this.selfCheckBean[name].picUrl.push(imageData);
        } else {
          this.selfCheckBean[name].picUrl[i] = imageData;
        }
        return;
      }
      const options: FileUploadOptions = {};
      let serverUrl = encodeURI(appConfig.IP_URL + appConfig.API.upload);
      //let serverUrl =  encodeURI('http://192.168.43.242:8080/upload/base.ctrl');
      options.fileKey = "file";
      options.fileName = "test.jpg";
      options.mimeType = "image/jpeg";
      const fileTransfer: FileTransferObject = this.transfer.create();
      fileTransfer.upload(imageData, serverUrl, options).then(restul => {
        let aa = JSON.parse(restul["response"]);
        if (aa["status"] == 200) {
          if (aa["data"].length > 0) {
            if (i == "c") {
              this.selfCheckBean[name].picUrl.push(aa["data"]);
            } else {
              this.selfCheckBean[name].picUrl[i] = aa["data"];
            }
          }
        }
        this.cd.detectChanges();
      });
    });
  }


  onHold(name, param) {
    let actionSheet = this.ActionSheet.create({
      buttons: [
        {
          text: "重拍",
          role: "重拍",
          handler: () => {
            let i = this.selfCheckBean[name].picUrl.indexOf(param);
            this.doCamera(name, i);
          }
        },
        {
          text: "查看大图",
          role: "查看大图",
          handler: () => {
            let url: string = param;
            this.photoViewer.show(
              encodeURI(
                this.appConfig.IP_URL + this.appConfig.API.getUpload + url
              ).replace("%5C", "/"),
              null,
              { share: false }
            );
          }
        },
        {
          text: "删除",
          handler: () => {
            let i = this.selfCheckBean[name].picUrl.indexOf(param);
            this.selfCheckBean[name].picUrl.splice(i, 1);
          }
        },
        {
          text: "取消",
          role: "取消",
          handler: () => { }
        }
      ]
    });
    actionSheet.present();
  }

  whaturl(url) {
    if ((url + "").indexOf("file") < 0) {
      return this.appConfig.IP_URL + this.appConfig.API.getUpload + url;
    } else {
      return url;
    }
  }

  getImgUrl(param) {
    this.selfCheckBean.maintUserSign = param.imageDate;
    this.selfCheckBean.maintUserSignTime = moment(new Date()).format(
        "YYYYMMDDHHmmss"
    );
  }

  getImgUrl2(param) {
    this.selfCheckBean.safeUserSign = param.imageDate;
    this.selfCheckBean.safeUserSignTime = moment(new Date()).format(
      "YYYYMMDDHHmmss"
    );
  }

  /**
   * 判断填空项中是否填写
   */
  verifyCheckItem(){
    let errorMessage : string = "请填写选项";
    if(this.selfCheckBean.twoPointOneOne.floorHeight.length == 0 ||
        this.selfCheckBean.twoPointOneOne.ladderHeight.length == 0 ||
        this.selfCheckBean.twoPointOneOne.includedAngle.length == 0){
      errorMessage += "2.1 (1) "
    }

    if(this.selfCheckBean.twoPointOneThree.doorWidth.length == 0 ||
        this.selfCheckBean.twoPointOneThree.doorHeight.length == 0){
      errorMessage += "2.1 (3), "
    }

    if(this.selfCheckBean.twoPointNineTwo.waitTime.length == 0){
      errorMessage += "2.9 (2), "
    }

    if(this.selfCheckBean.twoPointEleven.nominalVoltage1 == 0 ||
        this.selfCheckBean.twoPointEleven.insulationResistance1 == 0 ||
        this.selfCheckBean.twoPointEleven.nominalVoltage2 == 0 ||
        this.selfCheckBean.twoPointEleven.insulationResistance2 == 0 ||
        this.selfCheckBean.twoPointEleven.nominalVoltage3 == 0 ||
        this.selfCheckBean.twoPointEleven.insulationResistance3 == 0){
      errorMessage += "2.11, "
    }

    if(this.selfCheckBean.threeSevenOne.spacing == 0){
      errorMessage += "3.7 (1), "
    }

    if(this.selfCheckBean.threeSevenTwo.localHeight == 0 ||
        this.selfCheckBean.threeSevenTwo.distance == 0){
      errorMessage += "3.7 (2), "
    }

    if(this.selfCheckBean.threeFifteenFive.maxValue == 0 ||
        this.selfCheckBean.threeFifteenFive.measuredValue){
      errorMessage += "3.15 (5), "
    }

    if(this.selfCheckBean.fourNine.verticalHeight == 0 ||
        this.selfCheckBean.fourNine.width == 0){
      errorMessage += "4.9, "
    }

    if(this.selfCheckBean.fourTen.overloadCapacity == 0){
      errorMessage += "4.10, "
    }

    if(this.selfCheckBean.fiveOneOneThree.diameterRatio == 0){
      errorMessage += "5.1 (1)(3), "
    }

    if(this.selfCheckBean.sixThreeOne.maxClearance1 == 0){
      errorMessage += "6.3 (1), "
    }

    if(this.selfCheckBean.sixThreeTwo.maxClearance2 == 0){
        errorMessage += "6.3 (2), "
    }

    if(this.selfCheckBean.sixNineOneThree.minValue1 == 0){
      errorMessage += "6.9 (1)(3), "
    }

    if(this.selfCheckBean.sixTwelve.minValue2 == 0){
      errorMessage += "6.12, "
    }

    if(this.selfCheckBean.eightOne.equilCoefficient == 0){
      errorMessage += "8.1, "
    }
    if(errorMessage != "请填写选项"){
      let toast = this.commonFunc.showInsideErrorToast({
        errorMessage: errorMessage
      });
      toast.setDuration(300000);
      toast.setShowCloseButton(true);
      toast.present();
      return true;
    }
  }
}
